package com.guigu.qingcheng.service_user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.qingcheng.pojo.user.TbUser;
import com.guigu.qingcheng.service_user.mapper.TbUserMapper;
import com.guigu.qingcheng.service_user.service.TbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.qingcheng.utils.JwtUtils;
import com.guigu.qingcheng.utils.MD5;
import com.guigu.qingcheng.utils.R;
import org.springframework.util.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {
    @Autowired
    private TbUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Page<TbUser> findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        Page<TbUser> page1=new Page<TbUser>(page,size);
        QueryWrapper<TbUser> wrapper=queryWrapper(searchMap);
        IPage<TbUser> iPage = userService.page(page1, wrapper);
        return page1;
    }

    @Override
    public void sendSms(String mobile) {
        //1.得到六位短信验证码
        int max=999999;
        int min=100000;
        Random random = new Random();
        int code = random.nextInt(max);
        if(code<min){
            code=code+min;
        }
        System.out.println("短信验证码："+code);
//2.保存到redis里
        redisTemplate.boundValueOps("code_"+mobile).set(code+"");
        redisTemplate.boundValueOps("code_"+mobile).expire(5,
                TimeUnit.MINUTES);//5分钟失效
//3.发送给RabbitMQ
        Map<String,String> map=new HashMap();
        map.put("phone", mobile);
        map.put("code", code+"");
        rabbitTemplate.convertAndSend("","queue.sms",
                JSON.toJSONString(map));

    }

    @Override
    public R add(TbUser user, String smsCode) {
        //比较短信验证码
//获取系统短信验证码
        String sysCode= (String) redisTemplate.boundValueOps("code_"+user.getPhone()).get();
        if(sysCode==null){
            return R.error().data("error","验证码未发送或已过期");
        }
        if(!smsCode.equals(sysCode)){
            return R.error().data("error","验证码不正确");
        }
        if(user.getUsername()==null){
            user.setUsername(user.getPhone());
        }
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        if(baseMapper.selectCount(wrapper)>0) { //查询是否存在相同记录
            return R.error().data("error","该手机号已注册");
        }
        user.setCreated(new Date());
        user.setUpdated(new Date());
        user.setPoints(0);//积分初始值为0
        user.setStatus("1");//状态1
        user.setIsEmailCheck("0");//邮箱认证
        user.setIsMobileCheck("1");//手机认证
        baseMapper.insert(user);
        return R.ok();
    }

    @Override
    public String login(TbUser user) {
        // 获取登录手机和密码
        String phone = user.getPhone();
        String password = user.getPassword();

        //手机号和密码非空判断
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(phone)) {
            throw new RuntimeException("登录失败");
        }
        //判断手机号是否正确
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        List<TbUser> list = baseMapper.selectList(wrapper);
        if (list.size()==0) {
            throw new RuntimeException("登录失败");
        }
        //登录用户
        TbUser tbUser = list.get(0);

        // 判断密码
        // 因为存储到数据库密码是加密的
        // 把输入的密码进行加密，再和数据库密码进行比较
        // 加密方式MD5
        if (!MD5.encrypt(password).equals(tbUser.getPassword())) {
            System.out.println(MD5.encrypt(password));
            throw new RuntimeException("登录失败");
        }

        // 登录成功
        // 生成token字符串，使用jwt工具类
        String token = JwtUtils.getJwtToken(tbUser.getUsername(), tbUser.getNickName());
        return token;
    }

    @Override
    public TbUser getByOpenid(String openid) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        List<TbUser> list = baseMapper.selectList(wrapper);
        if (list.size()>0)
            return list.get(0);
        return null;
    }

    /**
     * 高级组合查询封装对象
     * @param searchMap
     * @return
     */
    public QueryWrapper<TbUser> queryWrapper(Map<String, Object> searchMap){
        QueryWrapper<TbUser> wapper = new QueryWrapper<TbUser>();
        if(searchMap != null){
            if(searchMap.get("password") != null && !"".equals(searchMap.get("password")))
                wapper.eq("password",searchMap.get("password"));
            if(searchMap.get("username") != null && !"".equals(searchMap.get("username")))
                wapper.like("username", "%" + searchMap.get("username") + "%");
            if(searchMap.get("phone") != null && !"".equals(searchMap.get("phone")))
                wapper.like("phone", "%" + searchMap.get("phone") + "%");
            if(searchMap.get("email") != null && !"".equals(searchMap.get("email")))
                wapper.like("email", "%" + searchMap.get("email") + "%");
            if(searchMap.get("created") != null && !"".equals(searchMap.get("created")))
                wapper.ge("created",searchMap.get("created"));
            if(searchMap.get("updated") != null && !"".equals(searchMap.get("updated")))
                wapper.le("updated",searchMap.get("updated"));
        }
        return wapper;
    }
}
